package cn.jdemo.io.inpustream;

import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @see InputStream 抽象基类
 * @see PipedInputStream
 * (1)PipedOutputStream(管道输出流)和PipedInputStream(管道输入流)配套使用；
 * (2)作用是***多线程可以通过管道进行线程间的通讯***；
 * (3)使用管道通信时，大致的流程是：
 *     PipedOutputStream对象与PipedInputStream对象通过connect方法绑定；
 *     线程A向PipedOutputStream中write()并调用PipedInputStream对象的receive()【这些数据就会发送过去】进而存储在PipedInputStream对象的缓冲中；
 *     此时，线程B读取PipedInputStream中的数据。
 *
 * // 构造方法
 * @see PipedInputStream#PipedInputStream() //
 * @see PipedInputStream#PipedInputStream(int)
 * @see PipedInputStream#PipedInputStream(PipedOutputStream) 
 * @see PipedInputStream#PipedInputStream(PipedOutputStream, int) 
 *
 * // 个性方法
 * @see PipedInputStream#connect(PipedOutputStream) 连接绑定的PipedOutputStream#connect()
 * @see PipedInputStream#receive(int) 绑定的PipedOutputStream#write方法内部是调用receive
 * @see PipedInputStream#receive(byte[], int, int)
 * @see PipedInputStream#receivedLast()
 *
 * @date 2020/12/21
 */
public class Demo08_PipedInputStream {
    public static void main(String[] args) throws Exception {
        test01();
    }
    public static void test01() throws Exception {
        ExecutorService es = Executors.newFixedThreadPool(2);

        PipedOutputStream pipedOS = new PipedOutputStream();
        es.execute(()->{
            try {
                Thread.sleep(1000L);
                pipedOS.write(97);
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        });

        PipedInputStream pipedIS = new PipedInputStream(pipedOS);
        int read = pipedIS.read();// 方法将阻塞，直到可用输入数据
        System.out.println(new Character((char)read));// a

        pipedOS.close();
        pipedIS.close();
        es.shutdown();

    }
}
